<template>
  <div class="grab-order-con table-gl-w">
    <div class="search-con search-w">
      <FilterTable :filterItem="filterItem" :isReset="true" :maxNum="4" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="sizeChange(20)">
        <template #headerLeft>
          <a-space>
            <!-- <div style="margin: 5px 0 5px 10px">合计任务：{{ statictsInfo.sumNum }}条 合计任务费用：￥{{ transNumberToShort(statictsInfo.amtSumAmount, 4) }} </div> -->
            <a-button class="gray-outline" @click="confirmTakeOrder">确认接单</a-button>
          </a-space>
        </template>
        <template #tableBody>
          <a-table size="mini" :bordered="{ headerCell: true }" v-model:selected-keys="ids" row-key="id" :row-selection="{ type: 'checkbox', showCheckedAll: true, onlyCurrent: false }" class="table-two-line" @sorter-change="sortChange" :data="tableList" :loading="loading" :pagination="false" :scroll="{ x: '100%', y: '100%' }">
            <template #columns>
              <a-table-column title="序号" #cell="{ rowIndex }" :width="50" fixed="left">{{ rowIndex + 1 }}</a-table-column>

              <a-table-column title="图片" #cell="{ record }" :width="60" fixed="left">
                <ImgPopover :src="imgUrl(record)">
                  <template #con>
                    <a-image :preview="false" width="40" height="40" fit="contain" :src="imgUrl(record)" />
                  </template>
                </ImgPopover>
              </a-table-column>
              <a-table-column title="SKU" #cell="{ record }" :width="150" fixed="left">
                <TextLimit position="top" :rows="1">{{ $extract(record, 'product.sku') }}</TextLimit>
              </a-table-column>
              <a-table-column title="SPU/类目" #cell="{ record }" :width="100">
                <TextLimit position="top" :rows="1">{{ $extract(record, 'product.spu') }}</TextLimit>
                <TextLimit position="top" :rows="1">{{ $extract(record, 'product.category.name') }}</TextLimit>
              </a-table-column>
              <a-table-column title="采购下单" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="product.gmtPurchase"> {{ $setTime($extract(record, 'product.gmtPurchase'), 'YYYY-MM-DD HH:mm') }} </a-table-column>
              <a-table-column title="采购入库" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="product.gmtPurchaseWarehouse"> {{ $setTime($extract(record, 'product.gmtPurchaseWarehouse'), 'YYYY-MM-DD HH:mm') }} </a-table-column>
              <a-table-column title="货件发货" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="product.gmtShipmentShipped"> {{ $setTime($extract(record, 'product.gmtShipmentShipped'), 'YYYY-MM-DD HH:mm') }} </a-table-column>
              <a-table-column title="货件入库" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="product.gmtShippmentWarehouse"> {{ $setTime($extract(record, 'product.gmtShippmentWarehouse'), 'YYYY-MM-DD HH:mm') }} </a-table-column>
              <!-- <a-table-column title="任务类型" #cell="{ record }" :width="80">{{ typeMap[record.type] }} </a-table-column> -->
              <!-- <a-table-column title="任务费用" #cell="{ record }" :width="80">
                <div style="color: red">￥{{ record.amtbCost }}</div>
              </a-table-column> -->

              <a-table-column title="任务发起组织" #cell="{ record }" :width="120"> {{ $extract(record, 'companyShortName') }} </a-table-column>
              <a-table-column title="任务雇主" #cell="{ record }" :width="80"> {{ $extract(record, 'employer.name') }} </a-table-column>
              <a-table-column title="类型/ID" #cell="{ record }" :width="160">
                <div>{{ typeMap[record.type] }}</div>
                <a-space>
                  <div class="highlight cursor" @click="viewDetial(record)">{{ record.code }}</div>
                  <div v-if="$extract(record.taskRequire, 'isSample')">
                    <span style="color: #979797" class="icon icon-yangpin"></span>
                  </div>
                </a-space>
              </a-table-column>
              <a-table-column title="预计交付日期" #cell="{ record }" :width="130">
                <div>{{ $setTime(record.gmtPlanDelivery, 'YYYY-MM-DD') }}</div>
                <div v-if="record.gmtPlanDelivery">
                  <div style="color: red" v-if="!toCheckDay(record.gmtPlanDelivery).type">超时{{ toCheckDay(record.gmtPlanDelivery).day }}</div>
                  <div class="highlight" v-else>剩余{{ toCheckDay(record.gmtPlanDelivery).day }}</div>
                </div>
              </a-table-column>
              <!-- <a-table-column title="优先级" #cell="{ record }" :width="60">
                <div class="level-btn level-1" v-if="record.priority === 'URGENT'"> 急 </div>
                <div class="level-btn level-2" v-else-if="record.priority === 'HIGH'"> 高 </div>
                <div class="level-btn level-3" v-else-if="record.priority === 'MIDDLE'"> 中 </div>
                <div class="level-btn level-4" v-else> 低 </div>
              </a-table-column> -->
              <a-table-column title="发布时间" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="gmtPublish">
                {{ $setTime(record.gmtPublish, 'YYYY-MM-DD HH:mm') }}
              </a-table-column>
              <a-table-column title="状态" #cell="{ record }" :width="130">
                {{ tabKeyMap[record.status] }}
              </a-table-column>

              <a-table-column title="留言" #cell="{ record }" :width="80">
                <a-space>
                  <div>{{ getNum(record.leaveMsgList) }}</div>
                  <div>
                    <div v-if="record.hasPartaNewLeaveMsg == null || record.hasPartaNewLeaveMsg == false">
                      <icon-message @click="showMsgModal(record)" class="cursor" :style="{ fontSize: '18px' }" />
                    </div>
                    <div v-else>
                      <a-badge :count="1" dot :offset="[2, -2]">
                        <icon-message @click="showMsgModal(record)" class="cursor" :style="{ color: '#f59a23', fontSize: '18px', verticalAlign: '-3px' }" />
                      </a-badge>
                    </div>
                  </div>
                </a-space>
              </a-table-column>
              <a-table-column title="操作" #cell="{ record }" :width="110" fixed="right">
                <a-button v-if="record.status" type="text" @click="viewDetial(record)">详情</a-button>
              </a-table-column>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size :total="pageNation.total" :default-page-size="pageNation.pageSize" :current="pageNation.pageNum" style="float: right" @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
  <msglist v-if="showMsgListModal" v-model="showMsgListModal" :info="taskDetailInfo" @save="getList" />
  <!-- 详情 -->
  <viewTaskDetail v-if="showViewTaskDetailModal" v-model="showViewTaskDetailModal" isTeamtype="isTeam" :info="taskDetailInfo" @save="getList" />
  <!-- 同意接单 -->
  <takeTask v-if="showTakeTaskModal" v-model="showTakeTaskModal" :list="selItemsList" :taskType="taskType" apiType="grabOrder" :ids="ids" @save="getList" />
</template>

<script lang="ts" setup>
  import { defineComponent, ref, onMounted } from 'vue'
  import { findNoTakeTaskPage, statTaskFromLocation } from '@/api/task'
  import { transNumberToShort } from '@/utils'
  import FilterTable from '@/components/TableFilter.vue'
  import TableWrap from '@/components/TableWrap.vue'
  import msglist from './components/msgList.vue'
  import viewTaskDetail from './components/viewDetail/viewdetailIndex.vue'
  import takeTask from './components/takeTask.vue'
  import _ from 'lodash-es'
  import { Message } from '@arco-design/web-vue'
  const typeMap = {
    NEW_PRODUCT_PICTURE: '新品套图',
    FIX_PICTURE: '以图修图',
    SHOOT_VIDEO: '拍摄视频',
    POSTER_SHOP_DESIGN: '海报设计',
    CHANGE_DIAMOND_COLOR: '换钻调色',
    HAND_DRAWN_DESIGN: '手绘设计',
  }

  const tabKeyMap = {
    WAIT_PUBLISH: '待发布',
    WAIT_ACCEPT: '待接单',
    SENDING_SAMPLE: '送样中',
    WAIT_SCHEDULE: '待排期',
    EXECUTING: '执行中',
    WAIT_VERIFY: '待验收',
    FINISHED: '已完成',
    NEGOTIATE_TERMINATED: '协商终止',
    TERMINATED: '已终止',
  }
  const filterItem: any = ref([
    {
      type: 'input_keyword',
      key: 'codeList',
      keyWidth: '90',
      value: ref(),
      placeholder: '请输入',
      label: '任务ID',
      width: 160,
      isMultiple: true,
    },
    {
      type: 'input_keyword_type',
      key: 'product.sku',
      keyItems: [
        { label: '产品SKU', value: 'product.sku' },
        { label: '产品SPU', value: 'product.spu' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '产品SKU',
      width: 160,
      isMultiple: true,
    },
    {
      type: 'input_keyword',
      key: 'companyName',
      keyItems: [
        { label: '任务发起组织', value: 'companyName' },
        // { label: '任务创建人', value: 'createUname' },
      ],
      keyWidth: '110',
      value: ref(),
      placeholder: '请输入',
      label: '任务ID',
      width: 160,
    },

    {
      key: 'taskType',
      label: '任务类型',
      value: ref(),
      type: 'select',
      width: 140,
      optionItems: [
        { label: '新品套图', value: 'NEW_PRODUCT_PICTURE' },
        { label: '以图修图', value: 'FIX_PICTURE' },
        { label: '拍摄视频', value: 'SHOOT_VIDEO' },
        { label: '海报/店招设计', value: 'POSTER_SHOP_DESIGN' },
      ],
      attrs: {
        'allow-clear': true,
      },
    },
    {
      type: 'keyword_date_range_custom',
      key: 'gmtPlanDelivery',
      keyItems: [{ label: '预计交付日期', value: 'gmtPlanDelivery' }],
      keyWidth: '110',
      label: '预计交付日期',
      value: ref(),
      width: 200,
    },
    {
      type: 'keyword_date_range',
      key: 'gmtPublish',
      keyItems: [{ label: '发布时间', value: 'gmtPublish' }],
      keyWidth: '110',
      value: ref(),
      width: 200,
    },
    {
      type: 'keyword_date_range_custom',
      key: 'gmtPurchase',
      keyItems: [
        { label: '采购下单时间', value: 'product.gmtPurchase' },
        { label: '采购入库时间', value: 'product.gmtPurchaseWarehouse' },
        { label: '货件发货时间', value: 'product.gmtShipmentShipped' },
        { label: '货件入库时间', value: 'product.gmtShippmentWarehouse' },
      ],
      keyWidth: '110',
      label: '采购下单时间',
      value: ref(),
      width: 200,
    },
    // {
    //   key: 'priority',
    //   label: '优先级',
    //   value: ref(),
    //   type: 'select',
    //   width: '100%',
    //   optionItems: [
    //     { label: '急', value: 'URGENT' },
    //     { label: '高', value: 'HIGH' },
    //     { label: '中', value: 'MIDDLE' },
    //     { label: '低', value: 'LOW' },
    //   ],
    //   attrs: {
    //     'allow-clear': true,
    //   },
    // },
  ])
  let statictsInfo: any = ref({})
  let pageNation = ref({ total: 0, pageNum: 1, pageSize: 20 })
  let searchValue: any = ref({})
  let ids = ref<Array<string>>([])
  let taskDetailInfo = ref({})
  let tableList = ref([])
  let loading = ref(false)
  let showMsgListModal = ref(false)
  let showViewTaskDetailModal = ref(false)
  let showTakeTaskModal = ref(false)
  let taskType = ref('')
  let selItemsList: any = ref([])

  const searchByVal = (info: any) => {
    searchValue.value = _.cloneDeep(info)
    if (searchValue.value.startDate) {
      searchValue.value.startDate = new Date(searchValue.value.startDate).valueOf()
      searchValue.value.endDate = new Date(searchValue.value.endDate).valueOf()
    }
    if (searchValue.value.codeList) {
      searchValue.value.codeList = searchValue.value.codeList.split(',')
    }

    // if (searchValue.value.gmtPurchase123) {
    //   searchValue.value.gmtExpectDeliveryStart = new Date(`${searchValue.value.gmtPurchase123.split(',')[0]} 00:00:00`).valueOf()
    //   searchValue.value.gmtExpectDeliveryEnd = new Date(`${searchValue.value.gmtPurchase123.split(',')[1]} 23:59:59`).valueOf()
    // } else {
    //   delete searchValue.value.gmtExpectDeliveryStart
    //   delete searchValue.value.gmtExpectDeliveryEnd
    // }

    getList()
  }
  const changePage = (val: number) => {
    pageNation.value.pageNum = val
    getList()
  }

  const sizeChange = (val: number) => {
    pageNation.value.pageNum = 1
    pageNation.value.pageSize = val
    getList()
  }

  const sortChange = (item: any, extra: any) => {
    if (extra) {
      searchValue.value.sortField = item
      searchValue.value.sortAsc = extra == 'ascend' ? true : false
    } else {
      searchValue.value.sortField = ''
      searchValue.value.sortAsc = ''
    }
    getList()
  }

  const toCheckDay = (time: any) => {
    let date = new Date(time).valueOf() + 24 * 60 * 60 * 1000
    let newDate = new Date().valueOf()
    let timeStr = 0
    if (date > newDate) {
      timeStr = date - newDate
    } else {
      timeStr = newDate - date
    }
    const formatTimeFromTimestamp = (timestamp: number) => {
      let text = ''
      const days = Math.floor(timestamp / (60 * 60 * 24 * 1000))
      const hours = Math.floor((timestamp % (60 * 60 * 24 * 1000)) / (60 * 60 * 1000))
      text = days > 0 ? `${days}天${hours}小时` : `${Math.abs(hours)}小时`
      return text
    }
    if (date - newDate < 0) {
      return {
        type: false,
        day: formatTimeFromTimestamp(timeStr),
      }
    } else {
      return {
        type: true,
        day: formatTimeFromTimestamp(timeStr),
      }
    }
  }

  const getNum = (list: any) => {
    if (list && list instanceof Array) {
      return list.length > 99 ? '99+' : list.length
    } else {
      return '0'
    }
  }

  const showMsgModal = (info: any) => {
    taskDetailInfo.value = info
    showMsgListModal.value = true
  }

  const viewDetial = (info: any) => {
    taskDetailInfo.value = info
    showViewTaskDetailModal.value = true
  }

  const confirmTakeOrder = () => {
    if (!ids.value[0]) return Message.error('请选择任务')
    // let typeArr: Array<string> = []
    // ids.value.forEach((e: any) => {
    //   let item: any = tableList.value.find((item: any) => {
    //     return item.id == e
    //   })
    //   if (item && typeArr.indexOf(item.taskType) == -1) typeArr.push(item.type)
    // })
    // if (typeArr.length > 1) return Message.error('每次只能接相同类型的任务')
    // taskType.value = typeArr[0]

    selItemsList.value = []
    selItemsList.value = tableList.value.filter((item: any) => {
      return ids.value.indexOf(item.id) > -1
    })

    showTakeTaskModal.value = true
  }

  const getList = async () => {
    let params = {
      ...searchValue.value,
      pageNum: pageNation.value.pageNum,
      pageSize: pageNation.value.pageSize,
    }
    loading.value = true
    const res: any = await findNoTakeTaskPage(params)
    tableList.value = res.data?.records || []
    pageNation.value.total = res.data?.total || 0
    loading.value = false
    ids.value = []
  }

  const imgUrl = (data: any) => {
    let arr = data?.product?.productPicList || []
    return arr.length > 0 ? arr[0].url : ''
  }

  const getStaticsInfo = async () => {
    let params = {
      ...searchValue.value,
      statLocation: 'Y_GRAP_TASK',
    }
    const res: any = await statTaskFromLocation(params)
    if (res) {
      statictsInfo.value = res?.data || {}
    }
  }

  onMounted(() => {
    getList()
    getStaticsInfo()
  })
</script>

<style lang="less" scoped>
  .grab-order-con {
    height: calc(100vh - @headerHeight);
  }
</style>
